package com.yimixian.app.address;

import android.os.Bundle;
import android.support.v4.util.SparseArrayCompat;
import android.text.TextUtils;

import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.util.NetworkUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by zhilian-2 on 2015/10/9.
 */
public abstract  class ChooseAdOrStHttpActivity extends AbstractAddressActivity implements Callback<Response> {
    private SparseArrayCompat<String> mRequestKeyArray=new SparseArrayCompat<>();
    // TODO：support dialog show/hide
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public abstract void initRequestAPI();

    public abstract void onHttpSuccess(String url, JSONObject responseJson);

    public abstract void OnHttpFailure(String url, String errorMessage);

    public abstract void fetchDataFromNetwork(String key);

    /**
     * set request id (not required)
     * @param index
     * @param requestKey
     */
    public void setRequestKey(int index,String requestKey){
        mRequestKeyArray.put(index,requestKey);
    }

    /**
     * get request id (not required)
     * @param index
     * @return
     */
    public String getRequestKeyByIndex(int index){
        return mRequestKeyArray.get(index);
    }

    /**
     * if need,override this fun,fetch local data from db or file
     *
     * @param key
     * @return
     */
    public String fetchDataFromLocal(String key) {
        return SharedPreferencesHelper.getString(key);
    }

    /**
     * if need,override this fun,save data to db or file
     *
     * @param key
     * @param responseJson
     */
    public void saveData2Local(String key, String responseJson) {
        SharedPreferencesHelper.commitString(key, responseJson);
    }

    /**
     * fetch data from local or network
     *
     * @param isFetchFromNetWork
     * @param requestKey
     */
    public void fetchData(boolean isFetchFromNetWork, String requestKey) {
        if (isFetchFromNetWork) {
            if (checkNetWorkState()) {
                fetchDataFromNetwork(requestKey);
            }
        } else {
            fetchDataFromLocal(requestKey);
        }
    }

    /**
     * check network is avaliable for better battery performance
     *
     * @return
     */
    public boolean checkNetWorkState() {
        if (NetworkUtils.isNetworkAvaliable(SystemFramework.getInstance().getGlobalContext())) {
            return true;
        } else {
            UiUtils.showToast(getString(R.string.errcode_network_unavailable));
            return false;
        }
    }

    /**
     * retrofit sucess
     *
     * @param baseResponse
     * @param response
     */
    @Override
    public void success(Response baseResponse, Response response) {
        String url = response.getUrl();
        String json = "";
        JSONObject jsonObject = null;
        try {
            json = Strings.inputStream2String(response.getBody().in());
        } catch (Exception e) {
            e.printStackTrace();
            OnHttpFailure(url, SystemFramework.getInstance().getGlobalContext()
                    .getString(R.string.io_error));
            return;
        }

        if (!TextUtils.isEmpty(json)) {
            try {
                jsonObject = new JSONObject(json);

            } catch (JSONException e) {
                e.printStackTrace();
                OnHttpFailure(url, SystemFramework.getInstance().getGlobalContext()
                        .getString(R.string.json_error));
                return;
            }
        }

        //返回error信息
        if (jsonObject != null){
            JSONObject errorObject = jsonObject.optJSONObject("error");
            if (errorObject != null){//返回错误信息
                com.yimixian.app.rest.response.Error error = new com.yimixian.app.rest.response.Error();
                error.code = errorObject.optInt("code");
                error.message = errorObject.optString("message");
                if (!TextUtils.isEmpty(error.message)) {
                    UiUtils.showToast(error.message);
                    OnHttpFailure(url, error.message);
                    return;
                }
            }
        }

        onHttpSuccess(url, jsonObject);
    }

    /**
     * retrofit failure
     *
     * @param error
     */
    @Override
    public void failure(RetrofitError error) {
        UiUtils.showToast(SystemFramework.getInstance().getGlobalContext()
                .getString(R.string.network_error));
        OnHttpFailure(error.getUrl(), error.getMessage());
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
